<template>
  <div class="left-center-container">
    <!-- 标题区域 -->
    <div class="title-left">告警通知</div>
    
    <div v-if="pageflag" class="alarm-notifications">
      <!-- 告警通知列表 -->
      <div class="notification-list">
        <div v-for="(alarm, index) in alarmList" :key="index" class="notification-item">
          <div class="notification-content">
            <!-- 上行：级别和时间 -->
            <div class="notification-header">
              <div class="alarm-level">
                <span class="level-badge" :class="'level-' + alarm.alarmLevel">{{ getAlarmLevelText(alarm.alarmLevel) }}</span>
              </div>
              <div class="alarm-time">
                {{ formatDateTime(alarm.createdAt) }}
              </div>
            </div>
            <!-- 下行：监测点信息 -->
            <div class="notification-body">
              {{ getPointName(alarm.radarPointId) }}，{{ getAlarmTypeText(alarm.alarmType) }}值超过【{{ getAlarmLevelText(alarm.alarmLevel) }}】预警线，{{ getAlarmTypeText(alarm.alarmType) }}值{{ Math.abs(parseFloat(alarm.currentValue || 0)) }}mm
            </div>
          </div>
        </div>
      </div>
    </div>
    <Reacquire v-else line-height="200px" @onclick="getData">
      暂无
    </Reacquire>
  </div>
</template>

<script>
import { getAlarmPointLogsPage, getPointListByDeptId } from '@/api/xing-bian-screen/deformation-api'
import tokenManager from '@/utils/tokenManager'

export default {
  props: {
    radarId: {
      type: Number,
      default: 6
    }
  },
  data() {
    return {
      alarmList: [],
      pointList: [], // 存储测点列表数据
      pageflag: false,
      timer: null
    };
  },
  created() {
    this.getData();
    // 设置定时器，每30秒刷新一次数据
    this.timer = setInterval(() => {
      this.getData();
    }, 30000);
  },
  watch: {
    radarId: {
      handler(newRadarId) {
        if (newRadarId) {
          this.getData();
        }
      },
      immediate: false
    }
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    async getData() {
      try {
        // 检查token有效性
        if (!tokenManager.isTokenValid()) {
          console.warn('Token无效，跳过数据请求');
          return;
        }
        
        // 并行获取告警数据和测点数据
        const [alarmResponse, pointResponse] = await Promise.all([
          getAlarmPointLogsPage({
            deptId: 1,
            radarId: this.radarId,
            pageIndex: 1,
            pageSize: 10000
          }),
          getPointListByDeptId({
            deptId: 1,
            radarId: this.radarId,
            pageNum: 1,
            pageSize: 100
          })
        ]);
        
        // 处理测点数据
        if (pointResponse && pointResponse.data && pointResponse.data.list) {
          this.pointList = pointResponse.data.list;
        }
        
        // 处理告警数据
        if (alarmResponse && alarmResponse.data && alarmResponse.data.list && alarmResponse.data.list.list) {
          this.alarmList = alarmResponse.data.list.list;
          this.pageflag = true;
        } else {
          this.pageflag = false;
        }
      } catch (error) {
        console.error('获取告警通知数据失败:', error);
        this.pageflag = false;
      }
    },
    
    // 格式化告警通知内容
    formatAlarmNotification(alarm) {
      const pointName = this.getPointName(alarm.radarPointId);
      const time = this.formatDateTime(alarm.createdAt);
      const alarmLevelText = this.getAlarmLevelText(alarm.alarmLevel);
      const alarmTypeText = this.getAlarmTypeText(alarm.alarmType);
      const currentValue = Math.abs(parseFloat(alarm.currentValue || 0));
      
      return `${time}，${pointName}，${alarmTypeText}值超过【${alarmLevelText}】预警线，${alarmTypeText}值${currentValue}mm，请及时处理；`;
    },
    
    // 格式化日期时间
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return '';
      
      const date = new Date(dateTimeStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      const second = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    getPointName(radarPointId) {
      // 首先尝试通过id字段匹配
      let point = this.pointList.find(p => p.id === radarPointId);
      if (point && point.pointName) {
        return point.pointName;
      }
      
      // 如果通过id没找到，再尝试通过pointIndex匹配
      point = this.pointList.find(p => p.pointIndex === radarPointId);
      if (point && point.pointName) {
        return point.pointName;
      }
      
      // 都没找到则返回默认名称
      return `监测点${radarPointId}`;
    },
    
    // 获取告警类型文本
    getAlarmTypeText(type) {
      const typeMap = {
        100: '形变',
        101: '速度',
        102: '加速度'
      };
      return typeMap[type] || '形变';
    },
    
    // 获取告警等级颜色
    getAlarmLevelColor(level) {
      const colorMap = {
        1: '#FF0000', // 红色
        2: '#FF6600', // 橙色
        3: '#00FF00', // 绿色
        4: '#0066FF'  // 蓝色
      };
      return colorMap[level] || '#999999';
    },
    
    // 获取告警等级文本
    getAlarmLevelText(level) {
      const textMap = {
        1: '一级',
        2: '二级',
        3: '三级',
        4: '四级'
      };
      return textMap[level] || '未知';
    }
  },
};
</script>

<style lang='scss' scoped>
.left-center-container {
  width: 100%;
  height: 100%;
  color: #fff;
  display: flex;
  flex-direction: column;
}

.title-left {
  color: white;
  font-size: 18px;
  font-weight: bold;
  background-image: url("../../../assets/xing-bian-screen/img/biaoti.png");
  background-size: contain;
  background-repeat: no-repeat;
  background-position: left center;
  padding-left: 60px;
  height: 50px;
  line-height: 50px;
  width: calc(100% - 60px);
  margin: 0 30px;
}

.alarm-notifications {
  height: calc(100% - 50px);
  display: flex;
  flex-direction: column;
  margin-top: 10px;
}

.notification-list {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 20px;
  padding: 0 30px;
  /* 隐藏滚动条 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.notification-list::-webkit-scrollbar {
  display: none; /* Chrome, Safari and Opera */
}

.notification-item {
  background: rgba(0, 100, 150, 0.3);
  padding: 12px 16px;
  margin-bottom: 10px;
  border-radius: 5px;
  
  &:hover {
    background: rgba(0, 100, 150, 0.5);
  }
}

.notification-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.alarm-level {
  .level-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 12px;
    font-weight: bold;
    font-size: 12px;
    color: #fff;
    
    &.level-1 {
      background-color: #FF0000; // 红色 - 一级
    }
    
    &.level-2 {
      background-color: #FF6600; // 橙色 - 二级
      color: #fff; // 橙色背景用白色文字
    }
    
    &.level-3 {
      background-color: #00FF00; // 绿色 - 三级
      color: #000; // 绿色背景用黑色文字
    }
    
    &.level-4 {
      background-color: #0066FF; // 蓝色 - 四级
    }
  }
}

.alarm-time {
  color: #ccc;
  font-size: 12px;
}

.notification-body {
  color: #ccc;
  font-size: 13px;
  line-height: 1.4;
  word-wrap: break-word;
  word-break: break-all;
}
</style>